package tool.zyk.spring.bean;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import tool.zyk.configuration.SimpleRpcConfiguration;
import tool.zyk.starter.ServerStarter;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.Objects;

/**
 * author: zyk
 * datetime: 2024/2/3 15:43
 * describe:
 */
@Slf4j
public class ServerBean implements ApplicationListener<ContextRefreshedEvent> {
    @Resource
    private SimpleRpcConfiguration simpleRpcConfiguration;

    private ServerStarter serverStarter;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        log.info("context start diy");
        if (Objects.isNull(serverStarter)) {
            this.serverStarter = new ServerStarter(simpleRpcConfiguration);
            serverStarter.start();
        }

    }

    @PreDestroy
    public void preDestroy() {
        if (Objects.nonNull(serverStarter)) {
            log.debug("simple-rpc server is close");
            serverStarter.close();
        }
    }
}
